package com.we.wfc.common.interceptor;

import com.google.common.collect.Lists;
import com.we.wfc.common.annotation.LoadCompleted;
import com.we.wfc.common.utils.ConverterUtil;
import com.we.wfc.common.utils.SpringContextUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Comparator;
import java.util.List;
import java.util.Map;

/**
 * @Description: SpringIoc初始化完成并被成功装载后的事件处理
 * @Author:Liangzy(Feeling)
 * @Date:Create in 2020/2/6 10:36 下午
 */
@Slf4j
@Component
public class InitializingBeanInterceptor implements ApplicationListener<ContextRefreshedEvent> {

    private boolean isStart = false;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        //保证只执行一次
        if (!isStart) {
            //获取当前程序实例
            ApplicationContext context = SpringContextUtil.getApplicationContext();
            if (ConverterUtil.isNotEmpty(context)) {
                //获取注解所标识的所有类
                Map<String, Object> beans = context.getBeansWithAnnotation(LoadCompleted.class);
                List<Object> compList = Lists.newArrayList();
                compList.addAll(beans.values());

                //比较权重
                Comparator<Object> compcomparator = (v1, v2) -> {
                    LoadCompleted w1 = v1.getClass().getAnnotation(LoadCompleted.class);
                    LoadCompleted w2 = v1.getClass().getAnnotation(LoadCompleted.class);
                    return Integer.compare(w1.weight(), w2.weight());
                };
                //权重越大越优先
                compList.sort(compcomparator.reversed());

                compList.forEach(x -> {
                    //获取到init函数
                    try {
                        Method init = x.getClass().getMethod("init", ApplicationContext.class);
                        if (ConverterUtil.isNotEmpty(init)) {
                            init.invoke(x, context);
                        }
                    } catch (Exception e) {
                        log.error("Error in init " + x, e);
                    }
                });

                //加载完成
                log.debug("LoadCompleted compontents loaded");
                isStart = true;
            }
        }
    }
}
